<?php if(!defined('MS_XTIGER')) exit('Access Denied');
/**
 * Created by openXtiger.org.
 * User: xtiger
 * Date: 2009-6-11
 * Time: 20:53:35
 */
 function databasemodel_insert(){
    $db = xt_load('db');
    $db->query("insert into xt_w(t) VALUES (1)");
 }
/*public */function databasemodel_multipage($sqlstr, $ordersql='', $page, $pageline = 20, $numcount = 5) {
    $db = xt_load('db');
    $idx = strpos(strtoupper($sqlstr),' FROM ');
    if($idx === FALSE) {
        return NULL;
    }
    $count = $db->result($db->query('SELECT COUNT(*) '.substr($sqlstr,$idx)));
    if(!$count) {
         return NULL;
    }
    $pageline = $pageline<1 ? 1 : $pageline;
    $realpages = @ceil($count / $pageline);
    $page =  $page < 1 ? $page=1 : $page > $realpages ? $realpages : $page;
    $start = ($page-1) * $pageline;

    $query = $db->query("$sqlstr $ordersql  LIMIT $start,$pageline");
    $result = array();
    while ($row = $db->fetch_array($query)) {
        $result[] = $row;
	}
    if($count<=$pageline) {
        return array('pagectrl'=>array($page, $count, $pageline, $realpages, 0, 0,$numcount), 'data'=>$result);//page,count,pageline,pagecount,from,to,query
    }
    $from = $page > $numcount ? $page - $numcount : 1;
    $to = $page < $realpages-$numcount ? $page + $numcount : $realpages;
    return array('pagectrl'=>array($page, $count, $pageline, $realpages, $from, $to,$numcount), 'data'=>$result);
}
/*public */function databasemodel_getwheres($intkeys, $strkeys, $randkeys, $likekeys) {

	$wherearr = array();
	$urls = array();

	foreach ($intkeys as $key=>$var) {
		$value = isset($_GET[$var])?$_GET[$var]:'';
		if(strlen($value)) {
			$wherearr[] = $key.'='.intval($value);
			$urls[] = "$var=$value";
		}
	}

	foreach ($strkeys as $key=>$var) {
		$value = isset($_GET[$var])?xt_stripsearchkey($_GET[$var]):'';
		if(strlen($value)) {
			$wherearr[] = "{$key}='$value'";
			$urls[] = "$var=".rawurlencode($value);
		}
	}

	foreach ($randkeys as $key=>$var) {
	    $value1 = isset($_GET[$var.'1'])?xt_stripsearchkey($_GET[$var.'1']):'';
	    $value2 = isset($_GET[$var.'2'])?xt_stripsearchkey($_GET[$var.'2']):'';
		if($value1) {
			$wherearr[] = "$key>='$var[0]($value1)'";
			$urls[] = "{$var}1=".rawurlencode($value1);
		}
		if($value2) {
			$wherearr[] = "$key<='$var[0]($value2)'";
			$urls[] = "{$var}2=".rawurlencode($value2);
		}
	}

	foreach ($likekeys as $key=>$var) {
		$value = isset($_GET[$var])?xt_stripsearchkey($_GET[$var]):'';
		if(strlen($value)>1) {
			$wherearr[] = "$key LIKE BINARY '%$value%'";
			$urls[] = "$var=".rawurlencode($value);
		}
	}
	return array('wherearr'=>$wherearr, 'urls'=>$urls);
}
/*public */function databasemodel_getorders($orders, $default) {
	$orders = array('sql'=>'', 'urls'=>array());
	$orderby = xt_get('orderby',$default);
	$ordersc = xt_get('ordersc','ASC');

	if(!empty($orderby) && isset($orders[$orderby])) {
		$orders['sql'] = " ORDER BY $orders[$orderby] $ordersc";
		$orders['urls'][] = "orderby=$orderby";
		$orders['urls'][] = 'ordersc='.strtolower($ordersc);
	}
	return $orders;
}
/*public */function databasemodel_fetchtablelist($tablepre='') {
    $db = xt_load('db');
    !$tablepre && $tablepre = '%';
    $tablepre = str_replace('_','\_',$tablepre);
    $query = $db->query("SHOW TABLE STATUS LIKE '$tablepre%'");
    $tables = $table = array();
	while($table = $db->fetch_array($query)) {
	    $tables[] = $table;
		/*if(*//*!in_array($table['Name'], $excepttables) && *//*!strexists($table['Name'], 'cache')) {
			$tables[] = $table;
		}*/
	}
	return $tables;
}

/*public */function databasemodel_version(){
    $db = xt_load('db');
    return intval($db->version());
}
/*public */function databasemodel_set($name, $value=''){
    $db = xt_load('db');
    return $db->query("SET $name='$value'");
}

/*public */function databasemodel_variable($name){
    $db = xt_load('db');
    $query = $db->query("SHOW VARIABLES LIKE '$name'");
    $v = $db->fetch_array($query, MYSQL_NUM);
    return count($v)>=2 ? $v[1] : '';
}
/*public */function databasemodel_sqldumptable($table, $startfrom = 0, $currsize = 0,
            $sqlcompat='', $sqlcharset ='', $dumpcharset='', $extendins=0, $filesize=0, $usehex=0, $complate=0) {
    $db = xt_load('db');
	$offset = 300;
	$tabledump = '';
	$tablefields = array();

	$query = $db->query('SHOW FULL COLUMNS FROM '.$table, 'SILENT');
	if (!$query && $db->errno() == '1146') {
		return '';
	} elseif (!$query) {
		$usehex = FALSE;
	} else {
		while($result = $db->fetch_array($query)) {
			$tablefields[] = $result;
		}
	}
	if(!$startfrom) {
		$createtable = $db->query('SHOW CREATE TABLE '.$table, 'SILENT');

		if(!$db->errno()) {
			$tabledump = "DROP TABLE IF EXISTS $table;\n";
		} else {
			return '';
		}

		$create = $db->fetch_row($createtable);
		$tabledump .= $create[1];
        $dbversion = $db->version();
		if($sqlcompat == 'MYSQL41' && $dbversion < '4.1') {
			$tabledump = preg_replace('/TYPE=(.+)/', "ENGINE=\\1 DEFAULT CHARSET=".$dumpcharset, $tabledump);
		}
		if($dbversion > '4.1' && $sqlcharset) {
			$tabledump = preg_replace('/(DEFAULT)*\s*CHARSET=.+/', 'DEFAULT CHARSET='.$dumpcharset, $tabledump);
		}

		$query = $db->query("SHOW TABLE STATUS LIKE '$table'");
		$tablestatus = $db->fetch_array($query);
		$tabledump .= ($tablestatus['Auto_increment'] ? " AUTO_INCREMENT=$tablestatus[Auto_increment]" : '').";\n\n";
		if($sqlcompat == 'MYSQL40' && $dbversion >= '4.1' && $dbversion < '5.1') {
			if(!empty($tablestatus['Auto_increment'])) {
				$temppos = strpos($tabledump, ',');
				$tabledump = substr($tabledump, 0, $temppos).' auto_increment'.substr($tabledump, $temppos);
			}

			if($tablestatus['Engine'] == 'MEMORY') {
				$tabledump = str_replace('TYPE=MEMORY', 'TYPE=HEAP', $tabledump);
			}
		}
	}

    $tabledumped = 0;
    $numrows = $offset;
    $firstfield = $tablefields[0];

    if($extendins == 0) {
        while($currsize + strlen($tabledump) + 500 < $filesize && $numrows == $offset) {
            if($firstfield['Extra'] == 'auto_increment'){
                $selectsql = 'SELECT * FROM '.$table." WHERE $firstfield[Field] > $startfrom LIMIT $offset";
            } else {
                $selectsql = 'SELECT * FROM '.$table." LIMIT $startfrom, $offset";
            }
            $tabledumped = 1;
            $query = $db->query($selectsql);
            $numfields = $db->num_fields($query);

            if($numrows = $db->num_rows($query)) {
                while($row = $db->fetch_row($query)) {
                    $dumpsql = $comma = '';
                    for($i = 0; $i < $numfields; ++$i) {
                        $dumpsql .= $comma.($usehex && !empty($row[$i]) && (strexists($tablefields[$i]['Type'], 'char') || strexists($tablefields[$i]['Type'], 'text')) ? '0x'.bin2hex($row[$i]) : '\''.mysql_escape_string($row[$i]).'\'');
                        $comma = ',';
                    }
                    if(strlen($dumpsql) + $currsize + strlen($tabledump) + 500 < $filesize ) {
                        if($firstfield['Extra'] == 'auto_increment') {
                            $startfrom = $row[0];
                        } else {
                            $startfrom ++;
                        }
                        $tabledump .= "INSERT INTO $table VALUES ($dumpsql);\n";
                    } else {
                        $complate = FALSE;
                        break 2;
                    }
                }
            }
        }
    } else {
        while($currsize + strlen($tabledump) + 500 < $filesize && $numrows == $offset) {
            if($firstfield['Extra'] == 'auto_increment'){
                $selectsql = 'SELECT * FROM '.$table." WHERE $firstfield[Field] > $startfrom LIMIT $offset";
            } else {
                $selectsql = 'SELECT * FROM '.$table." LIMIT $startfrom, $offset";
            }
            $tabledumped = 1;
            $query = $db->query($selectsql);
            $numfields = $db->num_fields($query);

            if($numrows = $db->num_rows($query)) {
                $extdumpsql = $extcomma = '';
                while($row = $db->fetch_row($query)) {
                    $dumpsql = $comma = '';
                    for($i = 0; $i < $numfields; ++$i) {
                        $dumpsql .= $comma.($usehex && !empty($row[$i]) && (strexists($tablefields[$i]['Type'], 'char') || strexists($tablefields[$i]['Type'], 'text')) ? '0x'.bin2hex($row[$i]) : '\''.mysql_escape_string($row[$i]).'\'');
                        $comma = ',';
                    }
                    if(strlen($extdumpsql) + $currsize + strlen($tabledump) + 500 < $filesize ) {
                        if($firstfield['Extra'] == 'auto_increment') {
                            $startfrom = $row[0];
                        } else {
                            $startfrom ++;
                        }
                        $extdumpsql .= "$extcomma ($dumpsql)";
                        $extcomma = ',';
                    } else {
                        $tabledump .= "INSERT INTO $table VALUES $extdumpsql;\n";
                        $complate = FALSE;
                        break 2;
                    }
                }
                $tabledump .= "INSERT INTO $table VALUES $extdumpsql;\n";
            }
        }
    }
    $tabledump .= "\n";
	return array($complate,$startfrom,$tabledump);
}
/*pulbic */function databasemodel_sqlimport($sqldump,$dbcharset) {
    $sqlquery = splitsql($sqldump);
    $db = xt_load('db');
    unset($sqldump);
    $dbversion = $db->version();
    foreach($sqlquery as $sql) {
        $sql = syntablestruct(trim($sql), $dbversion > '4.1', $dbcharset);
        if(!empty($sql)) {
            $db->query($sql, 'SILENT');
            if($db->error() && $db->errno() != 1062) {
                //$_SGLOBAL['db']->halt('MySQL Query Error', $sql);
                return FALSE;
            }
        }
    }
    return TRUE;
}

/*private */function splitsql($sqldump) {
	$sql = str_replace("\r", "\n", $sqldump);
	$num = 0;
	$ret = array('0'=>'');

	$queriesarray = explode(";\n", trim($sql));
	unset($sql);
	foreach($queriesarray as $query) {
		$queries = explode("\n", trim($query));
		foreach($queries as $subquery) {
			if(!empty($subquery[0])){
				$ret[$num] .= $subquery[0] == '#' ? NULL : $subquery;
			}
		}
		$num++;
		$ret[$num] = '';
	}
	return $ret;
}
/*private */function syntablestruct($sql, $version, $dbcharset) {
	if(strpos(trim(substr($sql, 0, 18)), 'CREATE TABLE') === FALSE) {
		return $sql;
	}
	$sqlversion = strpos($sql, 'ENGINE=') === FALSE ? FALSE : TRUE;

	if($sqlversion === $version ) {
		return $sqlversion && $dbcharset ? preg_replace(array('/ character set \w+/i', '/ collate \w+/i', '/DEFAULT CHARSET=\w+/is'), array('', '', "DEFAULT CHARSET=$dbcharset"), $sql) : $sql;
	}
	if($version) {
		return preg_replace(array('/TYPE=HEAP/i', '/TYPE=(\w+)/is'), array("ENGINE=MEMORY DEFAULT CHARSET=$dbcharset", "ENGINE=\\1 DEFAULT CHARSET=$dbcharset"), $sql);
	} else {
		return preg_replace(array('/character set \w+/i', '/collate \w+/i', '/ENGINE=MEMORY/i', '/\s*DEFAULT CHARSET=\w+/is', '/\s*COLLATE=\w+/is', '/ENGINE=(\w+)(.*)/is'), array('', '', 'ENGINE=HEAP', '', '', 'TYPE=\\1\\2'), $sql);
	}
}



?>